package com.we.web.filter;

import com.we.entity.User;
import com.we.service.impl.UserServiceImpl;
import com.we.util.Base64Utils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 访问权限过滤器
 */
public class PermissionFilter implements Filter {

    Cookie cookie = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        User user = (User) req.getSession().getAttribute("user");
        // 如果从session中获取user为空，才需要获取cookie进行登陆以及存放到session中,否则直接放行
        if(user!=null){
            chain.doFilter(request,response);
        }

        if (user == null) {
            Cookie[] cookies = req.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie c : cookies) {
                    if ("autoUser".equals(c.getName())) {
                        cookie = c;
                        break;
                    }
                }
                resp.sendRedirect(req.getContextPath()+"/login.html");
                return;
            }
        }

        //存在自动登录信息
        if (cookie != null) {
            String[] value = cookie.getValue().split(":");
            User u = new User();
            u.setUserName(value[0]);
            u.setPassword(Base64Utils.decode(value[1]));
            User loginUser = new UserServiceImpl().login(u);
            if (loginUser != null) {
                //登陆成功
                req.getSession().setAttribute("user", loginUser);
                chain.doFilter(request,response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
